/**
 * Created by 凡 on 6/2/2016.
 */
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var path=require('path');


var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
var fs = require('fs');

var fn = require('./lib/global');
var upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            var folder='files';
            fs.stat('./uploads/' + folder, (err, res)=> {
                if (err) {
                    fs.mkdir('./uploads/' + folder, ()=> {
                        cb(null, './uploads/' + folder);
                    })
                } else {
                    cb(null, './uploads/' + folder);
                }
            });
        },
        filename: function (req, file, cb) {
            cb(null, Date.now() + '.' + file.originalname.replace(/(.*)\./, ''));
        }
    })
});// for parsing multipart/form-data

Object.assign(global, fn);


app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded
app.use(cookieParser()); //cookie

app.use(cookieSession({keys: ['key']}));//session


app.use(express.static('dist'));
app.use('/uploads', express.static('uploads'));
app.use('/ueditor', require('./router/ueditor'));
app.use('/editor', express.static('ueditor'));
app.use('/login', require('./router/login'));
app.use('/nav', require('./router/nav'));
app.use('/tag', require('./router/tag'));
app.use('/page', require('./router/page'));
app.use('/article', require('./router/article'));
app.use('/category', require('./router/category'));
app.use('/post', require('./router/post'));

app.get('/imgUp', (req, res)=> {
    if (req.session.auth) {
        res.write('<h1>文件上傳</h1>');
        res.write('<form method="post" action="/upload" enctype="multipart/form-data">' +
            '<input type="file" name="files" multiple>' +
            '<button type="submit">tj</button>' +
            '</form>');
        res.end();
    }
    else res.redirect('/login');
});

app.post('/upload', (req, res, next)=> {
    if (req.session.auth) next();
    else res.redirect('/login');
}, upload.array('files'), (req, res)=> {
    let data = req.file || req.files;
    if (!Array.isArray(data)) {
        data = new Array(data);
    }
    let result = [];
    //,imgSet='';
    for (let i = 0, l = data.length; i < l; i++) {
        result[i] = {};
        result[i].name = data[i].originalname;
        result[i].url = data[i].destination + '/' + data[i].filename;
        //result[i].size=data[i].size;
        //result[i].type=data[i].mimetype;
        //imgSet+='<img src="'+result[0].src+'" alt="'+result[0].alt+'">\n';
    }
    res.json(result);
});
app.get('*', function(req, res){
    res.redirect('/');
});

app.listen(CONF.port);

log('server running at http://127.0.0.1:3000');
